package com.zshan.clinic.common.util.desensitization;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

public class MaskingSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private final Mask mask;

    public MaskingSerializer() { this.mask = null; }

    private MaskingSerializer(Mask mask) { this.mask = mask; }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (mask == null || value == null) {
            gen.writeString(value);
            return;
        }
        String out = value;
        switch (mask.type()) {
            case MOBILE: out = Desensitization.maskMobile(value); break;
            case ID_CARD: out = Desensitization.maskIdCard(value); break;
            case NAME: out = Desensitization.maskName(value); break;
            case EMAIL: out = Desensitization.maskEmail(value); break;
            case CUSTOM: out = Desensitization.maskKeep(value, mask.keepLeft(), mask.keepRight()); break;
            default: break;
        }
        gen.writeString(out);
    }

    /** 让序列化器拿到字段上的注解参数 */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (property != null) {
            Mask m = property.getAnnotation(Mask.class);
            if (m == null) {
                m = property.getContextAnnotation(Mask.class);
            }
            if (m != null) {
                return new MaskingSerializer(m);
            }
        }
        return this;
    }
}
